package me.siphone.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import me.siphone.http.api.QueryCallHistoryApi;
import org.linphone.R;

public class CallHistoryAdapter
        extends RecyclerView.Adapter<CallHistoryAdapter.CallHistoryViewHolder> {

    private List<QueryCallHistoryApi.CallHistory> callHistoryList;

    private OnReplyClickListener listener;

    public void setListener(OnReplyClickListener listener) {
        this.listener = listener;
    }

    public CallHistoryAdapter(List<QueryCallHistoryApi.CallHistory> callHistoryList) {
        this.callHistoryList = callHistoryList;
    }

    @NonNull
    @Override
    public CallHistoryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view =
                LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.adapter_call_history_item, parent, false);
        return new CallHistoryViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull CallHistoryViewHolder holder, int position) {
        QueryCallHistoryApi.CallHistory callHistory = callHistoryList.get(position);
        holder.tvCallContent.setText(callHistory.getRecordContent());
        holder.tvCallUsername.setText(callHistory.getUserName());
        holder.btnReplayEntrance.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (listener != null) {
                            listener.onReplyClick(callHistory);
                        }
                    }
                });
    }

    @Override
    public int getItemCount() {
        return callHistoryList.size();
    }

    public void addAll(List<QueryCallHistoryApi.CallHistory> list) {
        int startIndex = callHistoryList.size();
        callHistoryList.addAll(list);
        notifyItemRangeInserted(startIndex, list.size());
    }

    public interface OnReplyClickListener {
        void onReplyClick(QueryCallHistoryApi.CallHistory callHistory);
    }

    static class CallHistoryViewHolder extends RecyclerView.ViewHolder {

        TextView tvCallContent;
        TextView tvCallUsername;
        TextView btnReplayEntrance;

        public CallHistoryViewHolder(@NonNull View itemView) {
            super(itemView);
            tvCallContent = itemView.findViewById(R.id.tv_call_content);
            tvCallUsername = itemView.findViewById(R.id.tv_call_username);
            btnReplayEntrance = itemView.findViewById(R.id.tv_reply);
        }
    }
}
